package menu.lt.pers.menu;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Intent;

import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;


import android.os.Bundle;


import android.util.Log;
import android.view.*;
import android.widget.*;
import menu.lt.pers.menu.Bean.UserBean;
import menu.lt.pers.menu.dao.ResourceDao;
import menu.lt.pers.menu.dao.SoundUtils;
import menu.lt.pers.menu.dao.UserDao;


import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity {

    private Button btn_search;              //主页搜索按钮
    private ViewPager viewPager;
    private List<Fragment> fragmentList;    //存储fragment
    private int currentPage = 0;            //当前fragment页
    private Button btn_index;               //“主页”按钮
    private Button btn_kind;                //“分类”按钮
    private Button btn_my;                  //“我的”按钮
    private ActionBar actionBar;
    private LinearLayout linearLayout;
    private int current_bg;
    private SharedPreferences preference;
    private UserBean user;
    private Cursor cursor;
    private UserDao userDao;
    private boolean loginstate = false;
    private boolean music_flag = true;
    private MediaPlayer mediaPlayer;
    private UserDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.initView();                    //初始化 组件
        this.setListener();                 //设置监听器
        this.initActionbar();
        this.initUserData();

        //媒体播放器初始化
        SoundUtils.init(this);
        mediaPlayer = MediaPlayer.create(this,R.raw.bg_music);

    }

    private void initUserData() {
        preference = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isRemember = preference.getBoolean("isRemember", false);
        if (isRemember){
            String phone = preference.getString("phone", "");
            String pwd = preference.getString("pwd", "");
            Toast.makeText(MainActivity.this,pwd,Toast.LENGTH_SHORT).show();
            if (phone!=""){
                user = new UserBean();
                user.setPhone(phone);
                Cursor cursor = userDao.findByPhone(user);
                if(cursor.getCount()>0) {
                    cursor.moveToFirst();
                    if (cursor.getString(4).equals(pwd)){
                        int id = cursor.getInt(0);
                        String username = cursor.getString(1);
                        int isdelete = cursor.getInt(2);
                        String userhead = cursor.getString(3);
                        user.setId(id);
                        user.setUsername(username);
                        user.setUserhead(userhead);
                        user.setIsdelete(isdelete);
                        loginstate = true;
                        if (user.getUsername() == null || user.getUsername()==""){
                            Toast.makeText(MainActivity.this,"欢迎回来,亲~",Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this,"欢迎回来,"+user.getUsername()+"~",Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            }
        }
    }

    //设置监听器
    private void setListener() {
        //“主页”按钮监听器
        btn_index.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentPage = 0;
                viewPager.setCurrentItem(currentPage);
            }
        });
        //“分类”按钮监听器
        btn_kind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentPage = 1;
                viewPager.setCurrentItem(currentPage);
            }
        });
        //“我的”按钮监听器
        btn_my.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentPage = 2;
                viewPager.setCurrentItem(currentPage);
            }
        });
    }
    //初始化组件
    private void initView() {


        viewPager = findViewById(R.id.viewpager);
        btn_index= findViewById(R.id.btn_index);
        btn_kind= findViewById(R.id.btn_kind);
        btn_my= findViewById(R.id.btn_my);
        linearLayout = findViewById(R.id.main_linearlayout);

        userDao = new UserDao(MainActivity.this);


        //设置数据源
        fragmentList = new ArrayList<Fragment>();
        Fragment_index fragment_index = new Fragment_index();
        Fragment_kind fragment_kind = new Fragment_kind();
        Fragment_my fragment_my = new Fragment_my();

        //设置适配器
        fragmentList.add(fragment_index);
        fragmentList.add(fragment_kind);
        fragmentList.add(fragment_my);
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragmentList.get(i);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        };

        //绑定适配器
        viewPager.setAdapter(adapter);

        //viewpager对页面变化的监听器
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                Log.i("MainActivity.initView",
                        "当前页："+i + ",当前页偏移的百分比" + i + ",当前页偏移的像素位置" + i1);
            }

            //当页面切换时发生的动作
            @Override
            public void onPageSelected(int position) {
                Drawable drawable;

                drawable = getResources().getDrawable(R.drawable.index_default);
                drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());

                btn_index.setTextColor(Color.rgb(87,87,87));
                btn_index.setCompoundDrawables(null,drawable,null,null);

                drawable = getResources().getDrawable(R.drawable.kind_default);
                drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                btn_kind.setCompoundDrawables(null,drawable,null,null);
                btn_kind.setTextColor(Color.rgb(87,87,87));

                drawable = getResources().getDrawable(R.drawable.my_default);
                drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                btn_my.setTextColor(Color.rgb(87,87,87));
                btn_my.setCompoundDrawables(null,drawable,null,null);


                ActionBar actionBar = getActionBar();
                switch (position){
                    case 0:
                        currentPageEqual1();
                        break;
                    case 1:
                        currentPageEqual2();
                        break;
                    case 2:
                        currentPageEqual3();
                        break;
                }
                currentPage = position;
            }

            @Override
            public void onPageScrollStateChanged(int i) {
                // TODO Auto-generated method stub
            }
        });

        //读取用户设置
        preference = PreferenceManager.getDefaultSharedPreferences(this);
        current_bg = preference.getInt("current_bg",0);
        linearLayout.setBackgroundResource(ResourceDao.bg_list[current_bg]); //设置背景图片

        //登陆成功，跳转到第三个碎片
        user = getIntent().getParcelableExtra("user");
        if (user!=null){
            loginstate = true;
            Log.i("MainActivity.initView","当前登录用户："+user.getUsername());
            this.viewPager.setCurrentItem(2);
        }

    }

    //初始化 actionBar
    private void initActionbar(){
        actionBar = getActionBar();
        if (actionBar != null) {
//            LayoutInflater factory  = LayoutInflater.from(MainActivity.this);
            View layout = LayoutInflater.from(this).inflate(R.layout.action_bar,null);
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //Enable自定义的View
            actionBar.setCustomView(layout);//设置自定义的布局：actionbar_custom

            int color = Color.parseColor("#ffffff");
            ColorDrawable drawable = new ColorDrawable(color);
            actionBar.setBackgroundDrawable(drawable);

//            actionBar.setBackgroundDrawable();
            btn_search = layout.findViewById(R.id.btn_search);
            btn_search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this,Search_Activity.class);
                    startActivity(intent);
                }
            });
            Toolbar parent = (Toolbar) layout.getParent();
            parent.setContentInsetsAbsolute(0,0);
        }
    }
    //有关解决 fragment 获取activity 为null 的解决方法设置
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 只要发生onSaveInstanceState就remove all Fragment
        if(outState!=null){
            outState.remove("android:support:fragments");
        }
    }

    private void currentPageEqual3(){
        Drawable drawable;
        btn_my.setTextColor(Color.rgb(255,69,0));
        drawable = getResources().getDrawable(R.drawable.my_theme);
        drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
        btn_my.setCompoundDrawables(null,drawable,null,null);
        Bundle bundle = new Bundle();
        bundle.putParcelable("user",user);
        bundle.putBoolean("loginstate",loginstate);
        fragmentList.get(2).setArguments(bundle);
    }
    private void currentPageEqual2(){
        Drawable drawable;
        btn_kind.setTextColor(Color.rgb(255,69,0));
        drawable = getResources().getDrawable(R.drawable.kind_theme);
        drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
        btn_kind.setCompoundDrawables(null,drawable,null,null);
        Bundle bundle = new Bundle();
        bundle.putParcelable("user",user);
        bundle.putBoolean("loginstate",loginstate);
        fragmentList.get(1).setArguments(bundle);
    }
    private void currentPageEqual1(){
        Drawable drawable;
        btn_index.setTextColor(Color.rgb(255,69,0));
        drawable = getResources().getDrawable(R.drawable.index_theme);
        drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
        btn_index.setCompoundDrawables(null,drawable,null,null);
        Bundle bundle = new Bundle();
        bundle.putParcelable("user",user);
        bundle.putBoolean("loginstate",loginstate);
        fragmentList.get(0).setArguments(bundle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = new MenuInflater(MainActivity.this);
        inflater.inflate(R.menu.option_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_about:
                SoundUtils.boom();
                String sno = getResources().getString(R.string.sno);
                String sname = getResources().getString(R.string.sname);
                String program_function = getResources().getString(R.string.program_function);
                String version = getResources().getString(R.string.program_version);
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("关于");
                builder.setMessage("学号："+sno+"\n"+"姓名："+sname+"\n"
                        +"程序功能："+program_function+"\n"+"程序版本："+version);
                builder.setPositiveButton("ok", null);
                builder.show();
                break;
            case R.id.item_changebg:
                SoundUtils.boom();
                current_bg = (current_bg+1)%ResourceDao.bg_list.length;
                linearLayout.setBackgroundResource(ResourceDao.bg_list[current_bg]);
                @SuppressLint("CommitPrefEdits")
                SharedPreferences.Editor editor = preference.edit();
                Log.i("修改后的背景id",current_bg+"");
                editor.putInt("current_bg", current_bg);
                editor.apply();
                break;
            case R.id.item_music:
                SoundUtils.boom();
                if (music_flag==true){
                    mediaPlayer.start();
                } else mediaPlayer.pause();
                music_flag = !music_flag;
                break;
            default:
                Toast.makeText(MainActivity.this, "选择错误", Toast.LENGTH_LONG).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //如果当前为登录状态，则刷新界面 ，获取用户最新数据
        if (loginstate){
            Log.i("MainActivity.onResume","当前登录状态为: "+loginstate+"即将更新用户数据...");
            this.refreshListview();
            Log.i("MainActivity.onResume","即将将用户数据分发给碎片...");
            Bundle bundle = new Bundle();
            bundle.putParcelable("user",user);
            bundle.putBoolean("loginstate",loginstate);
            for(int i = 0;i<fragmentList.size();i++){
                fragmentList.get(i).setArguments(bundle);
            }
            Log.i("MainActivity.onResume","用户数据分发完毕...");
        }

    }
    //更新user数据
    private void refreshListview(){
        cursor = userDao.findByPhone(user);
        if(cursor.getCount()>0) {
            Log.i("MainActivity.refreshListview","刷新用户："+user.getUsername()+"数据");
            cursor.moveToFirst();
            int id = cursor.getInt(0);
            String username = cursor.getString(1);
            int isdelete = cursor.getInt(2);
            String userhead = cursor.getString(3);
            user.setId(id);
            user.setUsername(username);
            user.setUserhead(userhead);
            user.setIsdelete(isdelete);
            Log.i("MainActivity.refreshListview","更新完毕，当前登陆用户："+user.getUsername()+"数据");
        }
    }
}
